<template>
	<view class="bac-col-05">
		<!-- 加载中蒙版 -->
		<uni-transition mode-class="fade" :duration="500" :show="!dataLoaded" custom-class="vague-bg-9 mask-load">
		</uni-transition>
		<!-- 顶部导航 -->
		<!-- #ifdef MP-WEIXIN -->
		<view>
			<custom-navber titleSize="30rpx" :path="`/pages/user/myPage?usid=${activityData.user_id}`"
				:userGender="activityData.user_gender"
				:imgUrl="activityData.user_avatar|| 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'"
				:title="activityData.user_name || '匿名用户'"></custom-navber>
		</view>
		<!-- #endif -->
		<!-- 轮播 -->
		<!-- #ifdef MP-WEIXIN -->
		<view :style="{marginTop:menuObject.top + menuObject.height + 8 +'px'}" class="h-100">
		<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
			<view class="h-100">
			<!-- #endif -->
				<z-swiper ref="zSwiper" @slideChange="onChange" v-model="activityData.imgs" :options="options"
					:customStyle="{height:imageHeights[activeIndex] + 'px',transition: 'height 0.3s ease-in-out'}">
					<z-swiper-item v-for="(item,index) in activityData.imgs" :key="index" @click="previewImage(index)">
						<image class="w-100 h-100" :src="item.src" mode="widthFix"
							@load="(event) => onImageLoad(index, event)"
							:style="{height:'auto',transition: 'height 0.3s ease-in-out'}">
						</image>
					</z-swiper-item>
				</z-swiper>
			</view>
			<!-- 社群二维码弹窗 -->
			<uni-popup ref="groupPopup" type="center">
				<view class="group-popup-con">
					<image @click="saveQrcode"
						:src="activityData.group_qrcode && activityData.group_qrcode[0]?activityData.group_qrcode[0].src : ''"
						class="group-qrcode" />
					<view class="fs-28 fw-600 mt-5">微信扫码加入活动社群</view>
					<view class="fs-24 col-b1 mt-5">(点击二维码保存)</view>
				</view>
			</uni-popup>
			<!-- 报名信息弹窗 -->
			<uni-popup ref="signupPopup" type="bottom" border-radius="20rpx 20rpx 0 0">
				<view class="slanted-rectangle">
					<scroll-view class="h-40-vh ping-30" scroll-y>
						<view v-for="(item,index) in signupData" :key="index" :class="index == 0?'pt-0':''"
							class="flex-dir-row ali-item-cen flex-x-bet ping-20-0 bor-bottom-f3">
							<view class="flex-dir-row ali-item-cen">
								<qmy-gender-border iconBottom="4rpx" iconWidth="30rpx" iconHeight="30rpx" iconSize="24rpx" iconLineHeight="30rpx" :gender="item.user_gender" :avatar="item.user_avatar || 'https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/default-avatar.jpg'" :avatarWidth="100 + 'rpx'" :avatarHeight="100 + 'rpx'"></qmy-gender-border>
								</image>
								<view class="flex-dir-col flex-x-bet ml-20" style="height: 90rpx;">
									<view class="fs-32">{{item.user_name || '匿名用户'}}</view>
									<view class="fs-28 col-87">{{$formatDate(item.signup_time) || ''}}</view>
								</view>
							</view>
							<view @click="$NavigateTo(`/pages/user/myPage?usid=${item.user_id}`)"
								class="fs-28 col-00ba31">
								查看</view>
						</view>
					</scroll-view>
				</view>
			</uni-popup>
			<!-- uni-pay支付插件 -->
			<uni-pay @success="onPaySuccess" @fail="onPayFail" @close="onPayClose" mainColor="#14cc60"
				@create="onPayCreate" ref="pay"></uni-pay>
			<view class="bac-col-05 pos-rela bot-con">
				<image src="https://mp-22f314fc-fd0f-43b9-886e-ac79fe32303c.cdn.bspapp.com/image/bl.png"
					class="w-100 h-60 pos-abso img-min" />
				<view class="ping-20 w-100 pt-60 bac-col-f">
					<view class="fs-28 flex-dir-col flex-x-bet">
						<view class="fs-36 fw-600">{{activityData.name || ''}}</view>
						<view class="flex-dir-row ali-item-cen">
							<view v-for="tag in activityData.tags" :key="tag" class="text-tips bac-col-00b">
								{{tag}}
							</view>
						</view>
						<view class="flex-dir-row flex-x-bet ali-item-cen col-54 mt-20 pt-20 bor-top-f3 fw-600">
							<view class="flex-dir-row ali-item-cen">
								<view class="iconfont ic-baoming mr-10 fs-36"></view>
								<view>报名：{{$formatDate(activityData.signup_start_time) || ''}} -
									{{$formatDate(activityData.signup_end_time || '')}}
								</view>
							</view>
							<!-- 判断当前时间是否在报名时间范围前后,未开始、报名中、已结束 -->
							<view class="fs-24  text-ali-c "
								:class="activityData.signup_start_time < Date.now() && Date.now() < activityData.signup_end_time ? 'col-00ba31 start-con bac-col-68' : 'col-0a2e365e end-con bac-col-0a20a'">
								{{activityData.signup_start_time < Date.now() && Date.now() < activityData.signup_end_time ? '报名中' : activityData.signup_start_time < Date.now() ? '已结束' : '未开始'}}
							</view>
						</view>
						<view class="flex-dir-row flex-x-bet ali-item-cen col-54 mt-20 pt-20 bor-top-f3 fw-600">
							<view class="flex-dir-row ali-item-cen">
								<view class="iconfont ic-shijianxuanzeqi mr-10 fs-36"></view>
								<view>开始：{{$formatDate(activityData.start_time) || ''}} -
									{{$formatDate(activityData.end_time) || ''}}
								</view>
							</view>
							<view class="fs-24  text-ali-c "
								:class="activityData.start_time < Date.now() && Date.now() < activityData.end_time ? 'col-00ba31 start-con bac-col-68' : 'col-0a2e365e end-con bac-col-0a20a'">
								{{activityData.start_time < Date.now() && Date.now() < activityData.end_time ? '进行中' : activityData.start_time < Date.now() ? '已结束' : '未开始'}}
							</view>
						</view>
						<view class="flex-dir-row flex-x-bet ali-item-cen col-54 mt-20 pt-20 bor-top-f3 fw-600">
							<view class="flex-dir-row ali-item-cen">
								<view class="iconfont ic-weizhi mr-10 fs-36"></view>
								<view class="text-element-2">{{activityData.location || ''}}</view>
							</view>
							<!-- #ifdef MP-WEIXIN -->
							<view @click="nav"
								class="btn-bg br-10 flex-dir-row flex-center btn-dimensions flex-shrink-0">
								<view class="iconfont ic-luxian gradient-text"></view>
								<view class="gradient-text">导航</view>
							</view>
							<!-- #endif -->
						</view>
					</view>
				</view>
				<view class="mt-20 bac-col-f ping-20 pos-rela">
					<view class="flex-dir-row ali-item-cen flex-x-bet">
						<view class="fs-28 fw-600 flex-dir-row ali-item-cen">
							<view>已报名活动用户</view>
							<view class="ml-5">
								({{signupData.length || 0}}/{{activityData.people_num || 0}})
							</view>
						</view>
						<view @click="signupPopup" class="col-00ba31 fs-26 flex-dir-row ali-item-cen">
							<view>查看全部</view>
							<view class="iconfont ic-you fs-34 mt-5"></view>
						</view>
					</view>
					<liu-photo-list ref="photo" :dataList="signupData" @change="change"></liu-photo-list>
				</view>
				<view class="mt-20 bac-col-f pb-30" style="min-height:300rpx;">
					<view class="fs-28 fw-600 ping-20">活动详情</view>
					<mp-html :content="activityData.content || ''" />
				</view>
			</view>
			<!-- 底部导航 -->
			<view class="bottom-h bac-col-f w-100 bor-top-f3 bottom-nav-bg">
				<view class="flex-dir-row ali-item-cen flex-x-spa fs-24 text-ali-c">
					<view @click="call">
						<view class="iconfont ic-dianhua fs-50 fw-600 lh-50"></view>
						<view class="col-87 lh-30">电话</view>
					</view>
					<view @click="groupPopup">
						<view class="iconfont ic-qunliao fs-46 fw-600 lh-50"></view>
						<view class="col-87 lh-30">社群</view>
					</view>
					<!-- #ifdef MP-WEIXIN -->
					<button open-type="share">
						<view class="iconfont ic-fenxiang fs-50 fw-600 lh-50"></view>
						<view class="col-87 fs-24 lh-30">分享</view>
					</button>
					<!-- #endif -->
					<!-- #ifndef MP-WEIXIN -->
					<view @click="$Toast('H5暂不开放分享')">
						<view class="iconfont ic-fenxiang fs-46 fw-600 lh-50"></view>
						<view class="col-87 lh-30">分享</view>
					</view>
					<!-- #endif -->
					<view>
						<view v-if="signupData.length < activityData.people_num" @click="signUp"
							class=" br-200 text-ali-c "
							:class="signupStatus&& activityData.is_pay?'btntk-bg ping-10 fs-26':'btn-bg btn-hw fs-28'">
							<view class="gradient-text ">
								<view class="text-element-1">
									{{signupStatus ? '取消报名' : !signupStatus && activityData.is_pay ? `报名(￥${activityData.pay_amount / 100})` : '报名'}}
								</view>
								<view v-if="signupStatus && activityData.is_pay" class="fs-20 ">
									并退款￥{{activityData.pay_amount / 100}}</view>
							</view>
						</view>
						<view v-else @click="$Toast('抱歉，此活动已满员')" class="btn-bg br-200 text-ali-c btn-hw">
							<view class="gradient-text fs-28">已满员</view>
						</view>
					</view>
				</view>
			</view>
		</view>
</template>

<script>
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
import qmyGenderBorder from '../../components/qmy-gender-border/qmy-gender-border.vue';
	export default {
  components: { qmyGenderBorder },
		data() {
			return {
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: {
					top: 19,
					height: 28,
					width: 77
				},
				// #endif
				activityId: '', //活动id
				activityData: {}, //活动数据
				activeIndex: 0, //当前轮播图片索引
				imageHeights: [], // 用于存储每张图片的高度
				options: {
					autoHeight: false,
					initialSlide: 0, //初始显示的图片下标
					pagination: {
						el: true,
						type: 'bullets', //类型bullets 圆点（默认） fraction 分式 progressbar 进度条 custom 自定义
						dynamicBullets: true, //数量会部分隐藏
						clickable: true, //允许点击分页器
					},
					loop: false, //循环
				},
				signupData: [], //报名数据
				signupStatus: false, //报名状态
				dataLoaded: false, //数据加载完成
				// 支付参数开始
				type: "sign-up", // 支付回调类型 如 recharge 代表余额充值 goods 代表商品订单（可自定义，任意英文单词都可以，只要你在 uni-pay-co/notify/目录下创建对应的 xxx.js文件进行编写对应的回调逻辑即可）
				custom: {},
				// 支付参数结束
			};
		},
		computed: {
			userInfo() {
				return store.userInfo //用户信息
			},
		},
		onLoad(e) {
			this.activityId = e.id;
			this.getActivityDetail();
			this.getSignupData();
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.dataLoaded = false; //数据加载完成
			this.getActivityDetail();
			this.getSignupData();
		},
		onShow() {
			// 报名后返回时刷新报名数据
			this.getSignupData();
		},
		methods: {
			// 开始支付
			openPay() {
				// 防抖
				this.$debounce(() => {
					// 跳转支付收银台页
					let options = {
						total_fee: this.activityData
							.pay_amount, // 支付金额，单位分 100 = 1元（注意：因为是前端传的，此参数可能会被伪造，回调时需要再校验下是否和自己业务订单金额一致）
						order_no: this.generateOrderNumber(), // 业务系统订单号（即你自己业务系统的订单表的订单号）
						out_trade_no: this.generateOrderNumber() + '-1', // 插件支付单号
						description: this.removeEmoji(this.activityData.name) + '活动的报名费用', // 支付描述
						type: this.type, // 支付回调类型
						custom: {
							activity_id: this.activityData._id, // 活动id
						}, // 自定义数据
					};
					let optionsStr = encodeURI(JSON.stringify(options));
					this.$NavigateTo(`/pages/detail/pay-desk?options=${optionsStr}`);

					// 打开支付收银台
					// this.$refs.pay.open({
					// 	total_fee: this.activityData
					// 		.pay_amount, // 支付金额，单位分 100 = 1元（注意：因为是前端传的，此参数可能会被伪造，回调时需要再校验下是否和自己业务订单金额一致）
					// 	order_no: this.generateOrderNumber(), // 业务系统订单号（即你自己业务系统的订单表的订单号）
					// 	out_trade_no: this.generateOrderNumber() + '-1', // 插件支付单号
					// 	description: this.removeEmoji(this.activityData.name) + '活动的报名费用', // 支付描述
					// 	type: this.type, // 支付回调类型
					// 	custom: {
					// 		activity_id: this.activityData._id, // 活动id
					// 	}, // 自定义数据
					// });
				}, 500, true, "openPay")
			},
			// 唯一订单号生成函数
			generateOrderNumber() {
				const timestamp = Date.now(); // 获取毫秒级时间戳
				const randomNum = Math.floor(Math.random() * 1000000); // 6位随机数
				return `QMY${timestamp}${randomNum}`;
			},
			// 去除活动名称中的表情符号
			removeEmoji(text) {
				return text.replace(/[\u{1F600}-\u{1F64F}]/gu, '') // 表情符号
					.replace(/[\u{1F300}-\u{1F5FF}]/gu, '') // 符号、图标
					.replace(/[\u{1F680}-\u{1F6FF}]/gu, '') // 交通、地图符号
					.replace(/[\u{1F700}-\u{1F77F}]/gu, '') // 字母符号
					.replace(/[\u{1F780}-\u{1F7FF}]/gu, '') // 几何图形
					.replace(/[\u{1F800}-\u{1F8FF}]/gu, '') // 补充符号
					.replace(/[\u{1F900}-\u{1F9FF}]/gu, '') // 表情补充符号
					.replace(/[\u{2600}-\u{26FF}]/gu, '') // 杂项符号
					.replace(/[\u{2700}-\u{27BF}]/gu, ''); // 杂项符号
			},
			onPaySuccess() {
				this.$Toast('报名成功')
				// 刷新报名数据
				setTimeout(() => {
					this.getSignupData();
				}, 1000)
			},
			onPayFail() {
				this.$Toast('报名失败，如您已支付成功，请联系管理员退款')
			},
			onPayClose() {
				this.$Toast('支付取消')
			},
			// 图片预览
			previewImage(index) {
				uni.previewImage({
					urls: this.activityData.imgs.map(item => item.src),
					current: index
				});
			},
			// 报名信息弹窗
			signupPopup(status = true) {
				if (status) {
					this.$refs.signupPopup.open();
				} else {
					this.$refs.signupPopup.close();
				}
			},
			// 获取活动详情
			getActivityDetail() {
				this.$Route('get-public-data').getActivityDetail(this.activityId).then((res) => {
					this.activityData = res.data[0];
					uni.stopPullDownRefresh();
					this.dataLoaded = true; //数据加载完成
				}).catch((err) => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						this.$NavigateBack();
					}, 1600);
				});
			},
			// 获取报名数据
			getSignupData() {
				this.$Route('get-public-data').getSignupData(this.activityId).then((res) => {
					this.signupData = res.data;
					// 如果当前用户在报名数据中，则设置报名状态为已报名
					if (this.signupData.some(item => item.user_id == this.userInfo._id && item.signup_status ==
							0)) {
						this.signupStatus = true;
					} else {
						this.signupStatus = false;
					}
					this.$refs.photo.adjustMainInfoHeight()
				})
			},
			// 报名\取消报名
			signUp() {
				// 报名节流
				this.$debounce(() => {
					// 震动
					uni.vibrateShort();
					if (!this.signupStatus) {
						this.$Route('add-private-data').signUp(this.activityId)
							.then((res) => {
								this.$Toast(res.msg);
								setTimeout(() => {
									this.getSignupData();
								}, 1600);
							})
							.catch((err) => {
								console.error('遇到错误:', err); // 打印错误信息
								let {
									code,
									msg
								} = this.$parseError(err); // 调用公共解析方法
								if (code != 500 && msg != '付费活动请先支付') {
									this.$Toast(msg);
								} else {
									// 付费活动也走这里先校验一遍再打开支付窗口,支付成功增加报名数据时也会再校验一遍
									this.openPay();
								}
								setTimeout(() => {
									if (code === 401) {
										this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
									} else if (code === 400) {
										this.$NavigateTo('/pages/user/userPersonal'); // 跳转到个人信息页面
									}
								}, 1600);
							});

					} else {
						// 取消报名
						this.$Route('update-private-data').cancelSignUp(this.activityId).then((res) => {
							this.$Toast(res.msg)
							// 刷新报名数据
							setTimeout(() => {
								this.getSignupData();
							}, 1600)
						}).catch((err) => {
							console.error('遇到错误:', err); // 打印错误信息
							let {
								code,
								msg
							} = this.$parseError(err); // 调用公共解析方法
							this.$Toast(msg);
							setTimeout(() => {
								if (code === 401) {
									this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
								}
							}, 1600);
						});
					}
				}, 500, true, "signUp")
			},
			// 地图导航
			nav() {
				uni.openLocation({
					latitude: Number(this.activityData.location_lat),
					longitude: Number(this.activityData.location_lng), //保留5位小数
					name: this.activityData.location || '',
				})
			},
			// 社群二维码弹窗
			groupPopup() {
				// 判断用户是否报名
				if (!this.signupStatus) {
					this.$Toast('请先报名活动')
					return
				}
				if (!this.activityData.group_qrcode || !this.activityData.group_qrcode.length) {
					this.$Toast('此活动暂无社群')
					return
				}
				this.$refs.groupPopup.open();
			},
			// 保存社群二维码
			saveQrcode() {
				uni.downloadFile({
					url: this.activityData.group_qrcode[0].src || '',
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								this.$Toast('保存成功')
							}
						})
					}
				})
			},
			// 拨打电话
			call() {
				// 先判断用户是否已经报名
				if (!this.signupStatus) {
					this.$Toast('请先报名活动')
					return
				}
				uni.makePhoneCall({
					phoneNumber: this.activityData.contact_phone || this.activityData.user_mobile || ''
				})
			},
			change(id) {
				this.$NavigateTo(`/pages/user/myPage?usid=${id}`)
			},
			onChange() {
				//当前轮播图片索引
				this.activeIndex = this.$refs.zSwiper.swiper.activeIndex;
			},
			// 获取当前图片高度
			onImageLoad(index, event) {
				const {
					width,
					height
				} = event.detail;
				const screenWidth = uni.getSystemInfoSync().windowWidth;
				const scaledHeight = (screenWidth / width) * height; //根据屏幕宽度等比缩放扩大高度
				this.$set(this.imageHeights, index, scaledHeight);
			}
		}
	};
</script>

<style scoped>
	.shu-x {
		height: 25rpx;
		width: 1rpx;
		background: #f0f0f0;
	}

	.group-popup-con {
		padding: 20rpx;
		background: #ffffff;
		border-radius: 20rpx;
		text-align: center;
	}

	.group-qrcode {
		width: 350rpx;
		height: 350rpx;
	}

	.wh-45 {
		width: 45rpx;
		height: 45rpx;
	}

	.bot-con {
		margin-top: -60rpx;
		padding-bottom: calc(90rpx + env(safe-area-inset-bottom))
	}

	.end-con {
		width: 120rpx;
		height: 45rpx;
		border-radius: 10rpx;
		font-weight: normal;
		line-height: 45rpx;
	}

	.start-con {
		width: 120rpx;
		height: 45rpx;
		border-radius: 10rpx;
		font-weight: normal;
		line-height: 45rpx;
	}

	.img-min {
		top: 0;
		z-index: 1;
		height: 60rpx;
	}

	.text-tips {
		padding: 5rpx 10rpx;
		font-size: 22rpx;
		border-radius: 10rpx;
		color: #ffffff;
		margin-right: 10rpx;
		margin-top: 10rpx;
	}

	.bottom-nav-bg {
		position: fixed;
		bottom: 0;
		padding-top: 20rpx;
		z-index: 99999;
	}

	.btn-dimensions {
		width: 140rpx;
		height: 45rpx;
		line-height: 45rpx;
	}

	.btn-hw {
		width: 400rpx;
		height: 70rpx;
		line-height: 70rpx;
	}

	/* 退款按钮 */
	.btntk-bg {
		width: 400rpx;
		background: #0a2e36;
		height: auto;
		transition: transform 0.2s ease, box-shadow 0.2s ease;
	}

	.btntk-bg:active {
		transform: scale(0.9);
		/* 点击时按钮缩小 */
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
		/* 点击时添加阴影 */
	}

	.btn-bg:active {
		transform: scale(0.9);
		/* 点击时按钮缩小 */
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
		/* 点击时添加阴影 */
	}

	button {
		background-color: #ffffff00;
		padding: 0 !important;
		margin: 0 !important;
		line-height: 0rpx !important;
	}


	.slanted-rectangle {
		position: relative;
		width: 100%;
		background-color: white;
		border-top-left-radius: 40rpx;
		border-top-right-radius: 40rpx;
		padding-bottom: 20rpx;
		bottom: -20rpx;
		z-index: 2;
	}

	.slanted-rectangle::before {
		content: '';
		position: absolute;
		top: -25rpx;
		z-index: -1;
		left: 0;
		width: 100%;
		height: 50%;
		background-color: white;
		transform: skewY(3deg);
		border-radius: 40rpx 40rpx 0 0;
	}
</style>